from rest_framework import serializers
from rest_framework.serializers import ModelSerializer, IntegerField

from login.models import User, UserAddress, UserBlacklist, UserPreference, UserAuthHistory


class UserBlacklistSimpleSer(ModelSerializer):
    class Meta:
        model = UserBlacklist
        fields = "__all__"

class UserSerializer(ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'phone', 'real_name', 'id_card', 'status', 'register_time', 'avatar', 'type', 'created_at', 'updated_at', 'id_img_url']

class UserAddressSerializer(ModelSerializer):
    user_id = IntegerField(write_only=True)
    class Meta:
        model = UserAddress
        fields = ['id', 'address_type', 'phone', 'province', 'city', 'district', 'detail_address', 'is_default', 'created_at', 'updated_at', 'user_id']

    def validate_user_id(self, value):
        if not User.objects.filter(id=value).exists():
            raise serializers.ValidationError("关联的User不存在")
        return value

    def create(self, validated_data):
        user_id = validated_data.pop('user_id')
        user = User.objects.get(id=user_id)
        user_address = UserAddress.objects.create(user=user, **validated_data)
        return user_address

    def update(self, instance, validated_data):
        if 'user_id' in validated_data:
            user_id = validated_data.pop('user_id')
            user = User.objects.get(id=user_id)
            instance.user = user
        return super().update(instance, validated_data)
class UserPreferenceSer(ModelSerializer):
    class Meta:
        model = UserPreference
        fields = "__all__"
class UserAuthHistorySer(ModelSerializer):
    class Meta:
        model = UserAuthHistory
        fields = "__all__"